Basic Syntax
Learning Python Syntax
Understanding Python's syntax is similar to learning a new spoken language. Immersion and practice are key to becoming fluent:
- Vocabulary: Learn Python's keywords and functions.
- Grammar: Understand how to structure code correctly.
- Practice: Write and run code regularly to build proficiency.
Data Types in Python
Data types define the kind of value a variable holds and what operations can be performed on it. Python has several built-in data types.
Strings (str)
- Represent textual data enclosed in quotes.
- Example:
"Hello, World!" - Used for handling words, sentences, or any text.
Integers (int)
- Represent whole numbers without fractions.
- Example:
42 - Used for counting, indexing, and discrete calculations.
Floats (float)
- Represent real numbers with decimal points.
- Example:
3.1415 - Used for precise measurements and continuous calculations.
Determining Data Types
Use the type() function to check a value's data type:
type("Python") # Output: <class 'str'>
type(2021) # Output: <class 'int'>
type(9.81) # Output: <class 'float'>
Operations with Data Types
Performing operations depends on data type compatibility. Mixing incompatible types can cause errors.
Numeric Operations
- Addition:
5 + 3 # Output: 8 - Subtraction:
5 - 3 # Output: 2 - Multiplication:
5 * 3 # Output: 15 - Division:
5 / 2 # Output: 2.5
String Operations
- Concatenation: Combine strings using
+."Python " + "Programming" # Output: "Python Programming" - Repetition: Repeat strings using
*."Echo! " * 3 # Output: "Echo! Echo! Echo! "